package workqueues;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeoutException;
/**
 * 描述：任务有所耗时，并且有多个任务
 */
public class NewTask {
    private final static String TASK_QUEUE_NAME = "task_queue";
    public static void main(String[] args) throws IOException, TimeoutException {
        // 加载配置文件
        Properties properties = new Properties();
        properties.load(NewTask.class.getClassLoader().getResourceAsStream("application.properties"));
        // 创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 设置RabbitMQ地址
        factory.setHost(properties.getProperty("rabbitmq.host"));
        factory.setUsername(properties.getProperty("rabbitmq.username"));
        factory.setPassword(properties.getProperty("rabbitmq.password"));
        // 创建一个新的连接
        Connection connection = factory.newConnection();
        // 创建一个通道
        Channel channel = connection.createChannel();
        // 声明一个队列, durable=true表示持久化，也就是说队列会被存储在磁盘上，当消息代理重启时仍然存在
        channel.queueDeclare(TASK_QUEUE_NAME,true,false,false,null);
        for (int i = 0; i < 10; i++) {
            // 发送消息到队列中
            String message;
            if (i % 2 == 0) {
                message = "Hello RabbitMQ" + i + "....";
            } else {
                message = "Hello RabbitMQ" + i;
            }
            channel.basicPublish("",TASK_QUEUE_NAME,null,message.getBytes("UTF-8"));
            System.out.println("Send Message is:'" + message + "'");
        }
        // 关闭通道和连接
        channel.close();
        connection.close();
    }
}
